What are the access modifiers and their scopes in Java?
143
22-Jul-2024
Updated on 22-Jul-2024
Ashutosh Kumar Verma
22-Jul-2024Access Modifiers in Java
access modifiers are keywords used to describe the accessibility of classes, variables, methods, and constructors. There are four access modifiers in Java, each with its own scope of visibility.
public
The
public
modifier allows the widest access.Public members can be accessed from another class, regardless of relationship to a package or subclass.
Example-
public class MyClass { ... }
.protected
Protected
modifier allow subclasses (within the same package or different packages) to access within the same package.Without subclasses, classes in packages are inaccessible.
Example-
protected int num
default (no modifier)
The
default
access modifier (also known as package-private) means that no explicit modifier is used.It only allows access to the same package.
Example:
class AnotherClass { ... }
(without explicit variables) .private
The
private
modifier only restricts access to the same class.This is the most restrictive form of entry.
Example:
private String name
;It is important to check the visibility of classes and their members in Java programs, and to understand and properly use modifying methods.
Also, Read: Explain the difference between == and equals() in Java.